<template>
  <div class="container">
    <div class="table-header">
      <el-input clearable v-model.trim="roleName" :prefix-icon="Search" placeholder="角色名称搜索"
                class="input-with-select"
                style="width: 250px;margin-right: 50px;"/>
      <el-button type="primary" :icon="Search" @click="onSearch">
        搜索
      </el-button>
    </div>
    <span v-auth="{tag: '2'}" class="table-button">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">
        新增
      </el-button>
    </span>
    <el-dialog :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               v-model="dialogFormVisible"
               :title="dialogTitle"
               width="700">
      <el-form status-icon :model="form" ref="formRef" label-width="auto" :rules="rules" style="max-width: 400px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="form.roleName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleRemark">
          <el-input autosize type="textarea" placeholder="请输入角色描述" v-model="form.roleRemark" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel(formRef)">取消</el-button>
          <el-button type="primary" @click="dialogConfirm(formRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <div class="table-body">
      <el-table stripe :data="tableData" style="width: 100%" :row-style="{ height: '50px' }">
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
        <el-table-column prop="roleName" label="角色名称" width="auto"/>
        <el-table-column prop="roleRemark" label="角色描述" width="auto"/>
        <el-table-column prop="createTime" label="创建时间" width="auto"/>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button v-auth="{tag: '4'}" type="success" :icon="Edit" @click="handleEdit(scope.$index, scope.row)"/>
            <el-button v-auth="{tag: '4'}" type="warning" :icon="Operation" @click="handleRoleMenuBind(scope.row)"/>
            <el-button v-auth="{tag: '8'}" type="danger" :icon="Delete" @click="handleDelete(scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :total="total"
      />
    </div>
  </div>
  <RoleMenuBindView v-if="roleMenuBindVisible" v-model:roleMenuBindVisible="roleMenuBindVisible" :menu-id="menuId"
                    :role-id="roleId"
                    :role-name="roleMenuBindRoleName"/>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import RoleRequest from '@/api/sys/RoleApi.js';
import {CirclePlus, Delete, Edit, Operation, Search} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from "element-plus";
import RoleMenuBindView from "@/view/sys/role/RoleMenuBindView.vue";

let form = ref({});
let formRef = ref();
let dialogFormVisible = ref(false);
let roleMenuBindVisible = ref(false);
let dialogTitle = ref('新增');
let roleName = ref('');
let roleMenuBindRoleName = ref('');
let total = ref(0);
let menuId = ref(0);
let pageSize = ref(10);
let currentPage = ref(1);
let tableData = ref([]);
let roleId = ref(0);

onMounted(() => {
  menuId.value = history.state.m;
  getRoleList();
});

const getRoleList = () => {
  RoleRequest.queryRoleList({
    menuId: menuId.value,
    roleName: roleName.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }).then(res => {
    tableData.value = res.data;
    total.value = res.total;
  });
}

const handleRoleMenuBind = (row) => {
  roleMenuBindVisible.value = true;
  roleId.value = row.id;
  roleMenuBindRoleName.value = row.roleName;
}

const handleAdd = () => {
  form.value = {};
  dialogTitle.value = '新增';
  dialogFormVisible.value = true;
}

const handleEdit = (index, row) => {
  form.value = {...row};
  dialogTitle.value = '编辑';
  dialogFormVisible.value = true;
}

const dialogCancel = (formRef) => {
  dialogFormVisible.value = false;
  formRef.resetFields();
}

const dialogConfirm = (formRef) => {
  formRef.validate(val => {
    if (val) {
      RoleRequest.editRole({
        menuId: menuId.value,
        ...form.value
      }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        });
        getRoleList();
        formRef.resetFields();
        dialogFormVisible.value = false;
      });
    }
  });
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
      '操作不能撤回，确认继续吗？',
      '删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        RoleRequest.deleteRole(row.id, menuId.value)
            .then(() => {
              ElMessage({
                type: 'success',
                message: '删除成功',
              });
              getRoleList();
            })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消',
        });
      });
}

const onSearch = () => {
  currentPage.value = 1;
  getRoleList();
}

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getRoleList();
}

const rules = {
  roleName: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === void 0 || value === '') {
          callback(new Error('请输入角色名称'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  roleRemark: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === void 0 || value === '') {
          callback(new Error('请输入角色描述'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
}
</script>
